package com.zsw.Application.cron;

import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Scanner;

@Component
public class cronDayBackup {

    //    String sourceFolder = "E:\\d动力节点线上培训\\010-第十阶段微服务技术\\楠哥--cloud项目";
    String sourceFolder = null;
    String targetFolder = "E:\\savepath";

    @Scheduled(cron = "*/20 * * * * ?")
    public void cron() throws Exception {
        if (sourceFolder == null) {
            System.err.println("请输入备份路径");
            Scanner sc = new Scanner(System.in);
            sourceFolder = sc.next();
        }
        Path path1 = Paths.get(sourceFolder);
        LocalDateTime now = LocalDateTime.now();
        // 定义日期时间格式
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd-HH-mm-ss");
        // 将日期时间转换为字符串
        String formattedDate = now.format(formatter);
        Path path2 = Paths.get(targetFolder + "\\" + formattedDate);
        copyDirectory(path1, path2);
        System.out.println("备份成功: 时间" + formattedDate);
    }

    private static void copyDirectory(Path sourceFolderPath, Path targetFolderPath) throws IOException {
        // 创建目标文件夹，如果它不存在
        Files.createDirectories(targetFolderPath);

        // 获取源文件夹中的所有文件
        Files.walk(sourceFolderPath)
                .forEach(sourcePath -> {
                    // 获取源文件相对于源文件夹的路径
                    Path relativePath = sourceFolderPath.relativize(sourcePath);
                    // 合并目标路径
                    Path targetPath = targetFolderPath.resolve(relativePath);
                    try {
                        // 如果是文件，则复制
                        if (Files.isRegularFile(sourcePath)) {
                            Files.copy(sourcePath, targetPath);
                        } else {
                            // 如果是目录，创建它
                            Files.createDirectories(targetPath);
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                });
    }


}
